package com.canbot.u05.activity.agenda.calendar

import com.canbot.u05.MainApplication
import com.canbot.u05.R
import com.canbot.u05.activity.agenda.bean.AgendaBean
import com.canbot.u05.activity.agenda.bean.AgendaWorkDayBean
import com.canbot.u05.activity.agenda.dao.AgendaDataTable
import com.canbot.u05.activity.agenda.dao.AgendaDateTable
import com.canbot.u05.control.DataUtil
import java.util.*


/**
 * 判断两个date 是否是同一天
 */
fun isCommonDay(date1: Long, date2: Long): Boolean {
    val thisDate = getDate(date1)
    val otherDate = getDate(date2)
    return thisDate == otherDate
}


/**
 * 将表中数据转换为具体的日期
 */
fun getDateFromTable(date: String): IntArray {
    val list = date.split("-")
    val intArray = IntArray(3)
    intArray[0] = list[0].trim().toInt()
    intArray[1] = list[1].trim().toInt()
    intArray[2] = list[2].trim().toInt()
    return intArray
}


/**
 * 显示的时候，不显示年份
 * @author yinxiaowei
 * @date 2019/5/31
 */
fun getDateNoYearStr(agendaWorkDayBean: AgendaWorkDayBean): String {
    val arrayList = agendaWorkDayBean.data
    arrayList.sort()
    val size = arrayList.size
    var str = ""
    if (size > 0) {
        if (size > 3) {
            for (i in 0..2) {
                str += if (arrayList[i].week != -1) { //星期显示
                    "${translateWeekString(arrayList[i].week)},"
                } else { //日期显示
                    "${reduceYear(arrayList[i].date)},"
                }
            }
            var substring = str.substring(0, str.length - 1)
            substring += "..."
            str = substring
        } else {
            arrayList.forEach {
                str += if (it.week != -1) { //星期显示
                    "${translateWeekString(it.week)},"
                } else { //日期显示
                    "${reduceYear(it.date)},"
                }
            }
            val substring = str.substring(0, str.length - 1)
            str = substring
        }
    } else {
    }
    return str
}

private fun reduceYear(date: String): String {
    val split = date.split("-")
    return "${split[0]} - ${split[1]} - ${split[2]}"
}

/**
 * 检测添加的任务是否有时间冲突
 * // 先检测日期
 * // 再检测时间
 */
fun isExistTimeTask(list: MutableList<AgendaDateTable>, agendaBean: AgendaBean): AgendaDataTable? {
    val arrayList = agendaBean.workDay.data
    var isWeek = false
    if (arrayList[0].week != -1) { //待添加的日程是星期,需要将表中的日期转换为星期
        isWeek = true
    }
    for (agendaDate in list) {
        var dateEqual = false
        for (dateBean in agendaBean.workDay.data) {
            if (isWeek) {//待添加的日程是星期
                //比较星期，再将日期转换成星期进行比较
                if (agendaDate.week != -1) {
                    if (agendaDate.week == dateBean.week) {
                        dateEqual = true
                        break
                    }
                } else {
                    if (dateToWeek(agendaDate.date) == dateBean.week) {
                        dateEqual = true
                        break
                    }
                }
            } else {//待添加的日程是日期
                if (agendaDate.week != -1) {
                    if (agendaDate.week == dateToWeek(dateBean.date)) {
                        dateEqual = true
                        break
                    }
                } else {
                    if (agendaDate.date == dateBean.date) {
                        dateEqual = true
                        break
                    }
                }
            }
        }
        if (dateEqual) { // 如果日期相等，比较该日期表下的所有工作日期
            agendaDate.agendaDataTableList.forEach {
                val timeConfig = isTimeConflict(it.agendaBean, agendaBean)
                if (timeConfig) {
                    return it
                }
            }
        }
    }
    return null
}

/**
 * 比较工作日程的时间是否有冲突，关机的时间，没有结束时间
 */
private fun isTimeConflict(agendaBean: AgendaBean, agendaBeanNew: AgendaBean): Boolean {
    if (agendaBeanNew.endTime!! > agendaBean.startTime!! && agendaBeanNew.endTime!! < agendaBean.endTime!!) {
        return true
    } else if (agendaBeanNew.startTime!! > agendaBean.startTime!! &&
            agendaBeanNew.startTime!! < agendaBean.endTime!!) {
        return true
    } else if (agendaBeanNew.startTime!! < agendaBean.startTime!! && agendaBeanNew.endTime!! > agendaBean.endTime!!) {
        return true
    }
    return false
}

/**
 * 判断是不是过去的时间
 */
fun isTimeInValid(agendaBean: AgendaBean): Boolean {
    val workDay = agendaBean.workDay
    val currentDayStr = getDate(System.currentTimeMillis())
    val count = workDay.data.filter {
        currentDayStr == it.date
    }.count()
    if (count > 0) { //如果日期是当天
        val diff = agendaBean.startTime!! - System.currentTimeMillis()
        return diff <= 70 * 1000
    }
    return false
}

fun dataIsFull(agendaBean: AgendaBean): String {
    val agendaType = agendaBean.agendaType
    var count = 0
    // 验证工作类型
    when (agendaType.type) {
        MainApplication.getInstance().getString(R.string.shutdown),
/*        MainApplication.getInstance().getString(R.string.module_name_gbyd),
        MainApplication.getInstance().getString(R.string.module_name_ybjd),
        MainApplication.getInstance().getString(R.string.module_name_hbxc),*/
        MainApplication.getInstance().getString(R.string.module_name_kqdk) -> {
            count++
        }
        else -> {
            /*val data = agendaType.data
            if (data.size > 0) {
                count++
            } else {
                return MainApplication.getInstance().getString(R.string.agenda_type_details)
            }*/
            if (agendaType.type == MainApplication.getInstance().getString(R.string.choice_none)) {
                return MainApplication.getInstance().getString(R.string.agenda_type_details)
            } else {
                count++
            }
        }
    }
    // 验证工作时间
    val startTime = agendaBean.startTime
    if (startTime != null) {
        count++
    } else {
        return MainApplication.getInstance().getString(R.string.agenda_time_details)
    }
    // 验证工作日期
    val workDay = agendaBean.workDay
    if (workDay.data.size > 0) {
        count++
    } else {
        return MainApplication.getInstance().getString(R.string.agenda_date_details)
    }
    return ""
}

fun getTime(time: Long?): String {
    return if (time == null) {
        formateTime(0, 0)
    } else {
        val date = Date(time)
        val calendar = Calendar.getInstance()
        calendar.time = date
        val hour = calendar.get(Calendar.HOUR_OF_DAY)
        val minute = calendar.get(Calendar.MINUTE)
        formateTime(hour, minute)
    }
}

fun getDate(time: Long): String {
    val date = Date(time)
    val calendar = Calendar.getInstance()
    calendar.time = date
    val year = calendar.get(Calendar.YEAR)
    val month = calendar.get(Calendar.MONTH) + 1
    val day = calendar.get(Calendar.DATE)
    return formateDate(year, month, day)
}

fun getDateNoYear(time: Long): String {
    val date = Date(time)
    val calendar = Calendar.getInstance()
    calendar.time = date
    val month = calendar.get(Calendar.MONTH) + 1
    val day = calendar.get(Calendar.DATE)
    return formateDateNoyYear(month, day)
}

fun formateDateNoyYear(month: Int, day: Int): String {
    val strMonth: String = if (month < 10) {
        "0$month"
    } else {
        "$month"
    }
    val strDay: String = if (day < 10) {
        "0$day"
    } else {
        "$day"
    }
    return "$strMonth - $strDay"
}

fun formatDateStr(year: Int, month: Int): String {
    return "${year}年${month}月"
}

fun formateDate(year: Int, month: Int, day: Int): String {
    val strMonth: String = if (month < 10) {
        "0$month"
    } else {
        "$month"
    }
    val strDay: String = if (day < 10) {
        "0$day"
    } else {
        "$day"
    }
    return "$year - $strMonth - $strDay"
}

fun formateTime(hour: Int, minute: Int): String {
    val strHour: String = if (hour < 10) {
        "0$hour"
    } else {
        "$hour"
    }
    val strMinute: String = if (minute < 10) {
        "0$minute"
    } else {
        "$minute"
    }
    return "$strHour:$strMinute"
}

/**
 * 日期转换为星期
 */
fun dateToWeek(date: String): Int {
    val temps = date.replace(" ", "").split("-")
    val calendar = Calendar.getInstance()
    calendar.set(Calendar.YEAR, temps[0].toInt())
    calendar.set(Calendar.MONTH, temps[1].toInt() - 1)
    calendar.set(Calendar.DATE, temps[2].toInt())
    return translateCalendarWeek(calendar)
}

private fun translateCalendarWeek(calendar: Calendar): Int {
    var week = calendar.get(Calendar.DAY_OF_WEEK)
    when (week) {
        1 -> week = 7 //星期日
        2 -> week = 1
        3 -> week = 2
        4 -> week = 3
        5 -> week = 4
        6 -> week = 5
        7 -> week = 6 //星期六
    }
    return week
}

/**
 * 将星期转换成日期
 */
fun getWeekToDate(weekflag: Int): String {
    val time = calMethod(weekflag, System.currentTimeMillis())
    return getDate(time)
}

/**
 * @param weekflag 传入的是周几
 * @param dateTime 传入的是时间戳（设置当天的年月日+从选择框拿来的时分秒）
 * @return 返回起始闹钟时间的时间戳
 */
private val TAG = DataUtil::class.java.simpleName

private fun calMethod(weekflag: Int, dateTime: Long): Long {
    var time: Long = 0
    //weekflag == 0表示是按天为周期性的时间间隔或者是一次行的，weekfalg非0时表示每周几的闹钟并以周为时间间隔
    if (weekflag != 0) {
        val week = translateCalendarWeek(Calendar.getInstance())
        if (weekflag == week) {
//            if (dateTime >= System.currentTimeMillis()) {
//                time = dateTime
//            } else {
//                time = dateTime + 7 * 24 * 3600 * 1000
//            }
            time = dateTime
        } else if (weekflag > week) {
            time = dateTime + (weekflag - week) * 24 * 3600 * 1000
        } else if (weekflag < week) {
            time = dateTime + (weekflag - week + 7) * 24 * 3600 * 1000
        }
    } else {
        if (dateTime >= System.currentTimeMillis()) {
            time = dateTime
        } else {
            time = dateTime + 24 * 3600 * 1000
        }
    }
    return time
}

fun translateWeekIndex(pos: Int): Int {
    return when (pos) {
        0 -> 1
        1 -> 2
        2 -> 3
        3 -> 4
        4 -> 5
        5 -> 6
        else -> {
            7
        }
    }
}

fun translateWeekString(pos: Int): String {
    return when (pos) {
        1 -> MainApplication.getInstance().getString(R.string.week1)
        2 -> MainApplication.getInstance().getString(R.string.week2)
        3 -> MainApplication.getInstance().getString(R.string.week3)
        4 -> MainApplication.getInstance().getString(R.string.week4)
        5 -> MainApplication.getInstance().getString(R.string.week5)
        6 -> MainApplication.getInstance().getString(R.string.week6)
        else -> {
            MainApplication.getInstance().getString(R.string.week7)
        }
    }
}
